package com.net.requesthandler
{
	import com.net.http.HttpRequest;
	import com.net.http.HttpStateCode;
	import com.net.http.RequestHeader;
	import com.net.http.RequestStream;
	import com.net.requesthandler.IRequestHandler;
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	
	public class resourceRequestHandler implements IRequestHandler
	{
		private var request_header:RequestHeader;
		
		private var requeststream:RequestStream;
		
		private var request:HttpRequest;
		
		private var filestream:FileStream;//操作的文件流
		
		private var file:File;//操作的文件对象
		
		public function resourceRequestHandler()
		{
			
		}
		
		public function setRequest(client:HttpRequest):void
		{
			request=client;
			request_header=client.getRequestHeader();
			requeststream=client.getRequestStream();
			
			if(request_header.getRequestMode()=="GET"){
				loadFile();
			}else if(request_header.getRequestMode()=="POST"){
				request_header.setReponseHeader(HttpStateCode.BAD_REQUEST);
				requeststream.writeReponseHeader(request_header);
				request.close();
			}
		}
		
		private function loadFile():void{
			
			file=File.applicationDirectory.resolvePath(request_header.getFilePath());
			if(file.exists){
				
				filestream=new FileStream();
				filestream.addEventListener(ProgressEvent.PROGRESS,on_data_read);
				filestream.addEventListener(Event.COMPLETE,on_load_complete);
				
				request_header.setReponseHeader(HttpStateCode.OK,null,null,file.size);
				requeststream.writeReponseHeader(request_header);
				
				//读取文件
				filestream.openAsync(file,FileMode.READ);
			}else{
				//404
				request_header.setReponseHeader(HttpStateCode.NO_FOUND);
				requeststream.writeReponseHeader(request_header);
				request.close();
			}
		}
		
		
		//随时加载随时发送
		private function on_data_read(event:ProgressEvent):void{
			var bytes:ByteArray=new ByteArray();
			filestream.readBytes(bytes);
			requeststream.writeReponseBytes(bytes);
		}
		
		//加载并且发送完成
		private function on_load_complete(event:Event):void{
			filestream.close();
			request.close();
		}
	}
}